package com.yztc.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yztc.bean.home.ListFocusBean;
import com.yztc.bean.home.ListLcBean;
import com.yztc.bean.home.NewBannerListBean;
import com.yztc.bean.home.RollListBean;
import com.yztc.bean.home.TopBannerListBean;
import com.yztc.bean.home.UrlProductImageBean;
import com.yztc.chunboapp.MainActivity;
import com.yztc.chunboapp.R;
import com.yztc.ui.LoginActivity;
import com.yztc.ui.ServiceActivity;
import com.yztc.ui.details.DetailsActivity;
import com.yztc.ui.WebViewActivity;
import com.yztc.ui.home.adapter.HomeBaseAdapter;
import com.yztc.ui.home.adapter.HomeHRecycleViewAdapter;
import com.yztc.ui.home.adapter.HomePageAdapter;
import com.yztc.utils.DividerItemDecoration;
import com.yztc.utils.ImageHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by My on 2016/10/6.
 */
public class HomeFragment extends Fragment implements HomeConstract.IHomeView{
    //顶部的点击进入ImageButton
    private ImageButton mIBtnEnter;
    //广告轮播的图片集合
    private List<ImageView> imageViews;
    //广告轮播跟随的小圆点集合
    private List<ImageView> icons;
    //presenter中间操控类
    private HomePresenter mHomePresenter;
    //home页面的listView
    private ListView mListView;
    private View view;
    //引进的listView头布局
    private View headView;
    //引进的listView尾布局
    private View footView;
    //home页面的helllo图片
    private ImageView mImageViewHello;
    //home页面的轮播
    private ViewPager mViewPager;
    //home页面的轮播的小圆点父布局
    private LinearLayout mLinearLayout;
    //轮播下面的三张图片
    private ImageView mImageViewHot,mImageViewDaliy,mImageViewEat;
    //轮播下面的三张图片的父布局
    private LinearLayout mLineHot,mLineDaily,mLineEat;
    //整站精选和新品上市各两个标题
    private TextView mTVJingXuan,mTVSubJingXuan,mTVShangShi,mTVSubShangShi;
    //整站精选和新品上市各两个横向RecycleView
    private RecyclerView mRecJingXuan,mRecShangShi;
    //新品 上市下面 的两张图片和结尾各两张图片
    private ImageView mIVBiaoZhun,mIVMianFei,mIVLianMeng,mIVChunBo;
    //listview每个item的头部图片
    private ImageView mIVHead;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //跳转到下一个界面
            if (msg.what == 1) {
                int index = msg.arg1;
                mViewPager.setCurrentItem(index);
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home,null);
        headView = inflater.inflate(R.layout.home_listview_head,null);
        footView = inflater.inflate(R.layout.home_listview_foot,null);
        initView();
        mHomePresenter = new HomePresenter(this);
        mHomePresenter.loadData(getContext());
        //头部定位和进入登录页面的监听方法
        setOnClickListener();
        return view;
    }
    //头部定位和进入客服的监听方法
    private void setOnClickListener() {
        mIBtnEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.tag == true){
                    Intent intent = new Intent(getActivity(), ServiceActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void initView() {
        mImageViewHello = (ImageView) headView.findViewById(R.id.iv_hello);
        mListView = (ListView) view.findViewById(R.id.lv_home);
        mViewPager = (ViewPager) headView.findViewById(R.id.vp_lunbo);
        mLinearLayout = (LinearLayout) headView.findViewById(R.id.line_vp);
        mImageViewDaliy = (ImageView) headView.findViewById(R.id.iv_daily);
        mImageViewHot = (ImageView) headView.findViewById(R.id.iv_hot);
        mImageViewEat = (ImageView) headView.findViewById(R.id.iv_eat);
        mTVJingXuan = (TextView) headView.findViewById(R.id.tv_jingxuan);
        mTVSubJingXuan = (TextView) headView.findViewById(R.id.tv_sub_jingxuan);
        mTVShangShi = (TextView) headView.findViewById(R.id.tv_shangshi);
        mTVSubShangShi = (TextView) headView.findViewById(R.id.tv_sub_shangshi);
        mRecJingXuan = (RecyclerView) headView.findViewById(R.id.recyclerView_jingxuan);
        mRecShangShi = (RecyclerView) headView.findViewById(R.id.recyclerView_shangshi);
        mIVBiaoZhun = (ImageView) headView.findViewById(R.id.iv_biaozhun);
        mIVMianFei = (ImageView) headView.findViewById(R.id.iv_mianfei);
        mIVLianMeng = (ImageView) footView.findViewById(R.id.iv_lianmeng);
        mIVChunBo = (ImageView) footView.findViewById(R.id.iv_chunbo);
        mLineHot = (LinearLayout) headView.findViewById(R.id.line_hotsales);
        mLineDaily = (LinearLayout) headView.findViewById(R.id.line_dailyFood);
        mLineEat = (LinearLayout) headView.findViewById(R.id.line_todayEat);
        mIBtnEnter = (ImageButton) view.findViewById(R.id.ibtn_enter);
    }

    //view的回调，加载数据错误时，弹出提示信息
    @Override
    public void showErrorMsg(Throwable e) {
        Toast.makeText(getContext(),e.toString(),Toast.LENGTH_SHORT).show();
    }
    //view的回调，Hello图片
    @Override
    public void addHelloImage(final List<TopBannerListBean> topBannerList) {
        ImageHelper.getNormalImage(getContext(),topBannerList.get(0).getImage(),mImageViewHello);
        mListView.addHeaderView(headView);
        mListView.addFooterView(footView);
        //图片设置监听，实现跳转
        mImageViewHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",topBannerList.get(0).getLink());
                bundle.putString("title",topBannerList.get(0).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    //view的回调，返回广告轮播数据
    @Override
    public void addVPImages(final List<ListFocusBean> mListFocusBean) {
        //获取viewpager的图片
        imageViews = new ArrayList<>();
      for (int i=0;i<mListFocusBean.size();i++){
          ImageView iv = new ImageView(getContext());
          iv.setAdjustViewBounds(true);
          ImageHelper.getNormalImage(getContext(),mListFocusBean.get(i).getPicUrl(),iv);
          //为每个view设置监听，点击跳转
          final int finalI = i;
          final int finalI1 = i;
          iv.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  Intent intent = new Intent(getActivity(), WebViewActivity.class);
                  Bundle bundle = new Bundle();
                  bundle.putString("link",mListFocusBean.get(finalI1).getLink());
                  bundle.putString("title",mListFocusBean.get(finalI1).getTitle());
                  intent.putExtras(bundle);
                  startActivity(intent);
              }
          });
          imageViews.add(iv);
      }
        //调用初始化轮播小圆点集合的方法
        initIcons();
        //实现轮播的方法
        showLunBo();
        //vp适配数据
        HomePageAdapter adapter = new HomePageAdapter(imageViews);
        mViewPager.setAdapter(adapter);
    }

    //初始化轮播小圆点集合
    private void initIcons() {
        icons = new ArrayList<>();
        for (int i=0;i<imageViews.size();i++){
            ImageView iv = new ImageView(getContext());
            iv.setImageResource(R.mipmap.toudi);
            //动态设置imageView的尺寸
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(55,55);
            iv.setLayoutParams(params);
            //动态设置imageView的间距
            iv.setPadding(30,1,1,30);
            mLinearLayout.addView(iv);
            icons.add(iv);
        }

        icons.get(0).setImageResource(R.mipmap.toudi_grey);
    }
        //定义实现轮播的方法
    public void showLunBo(){
        //解决ViewPager第一次不能向左滑动的小bug
        mViewPager.setCurrentItem(1000 *imageViews.size());
        //设置ViewPager的界面切换监听方法
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {

                //设置小圆点的切换
                for (int i = 0; i < icons.size(); i++) {
                    icons.get(i).setImageResource(R.mipmap.toudi);
                    if (i ==  position % imageViews.size()){
                        icons.get(i).setImageResource(R.mipmap.toudi_grey);
                    }
                }
            }
        });
        //开始线程任务
        final AutoRunTask autoTask = new AutoRunTask();
        autoTask.startRun();

        //处理ViewPager的触摸事件
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            //当触摸屏幕的时候调用
            //MotionEvent:手指触摸到屏幕的时候,所触发的一系列的事件.
            //down,up,move,cancle.
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当手指触摸到ViewPager的时候,ViewPager的自动跳转会停止;
                //如果手指没有触摸ViewPager,ViewPager的自动跳转又会开始.
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://第一个被执行的事件
                        autoTask.stopRun();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        autoTask.startRun();
                        break;
                }
                //此处只能返回false
                return false;
            }
        });
    }

    //自定跳转的线程任务【轮播】
    class AutoRunTask implements Runnable {
        private int delayTime = 2000;
        private boolean isStart = false;
        //开始线程任务
        public void startRun() {
            if (!isStart) {
                //关闭之前所有正在执行的任务
                mHandler.removeCallbacks(this);
                isStart = true;
                mHandler.postDelayed(this, delayTime);
            }
        }

        //停止线程的方法【轮播】
        public void stopRun() {
            if (isStart) {
                isStart = false;
                mHandler.removeCallbacks(this);
            }
        }
        @Override
        public void run() {
            int currentItem = mViewPager.getCurrentItem();
            //发送消息
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = ++currentItem;
            mHandler.sendMessage(msg);
            //递归调用自身,形成循环.
            mHandler.postDelayed(this, delayTime);
        }
    }

    // view的回调,轮播下面的三张图片
    @Override
    public void addProductImages(final UrlProductImageBean urlProductImageBean) {
        ImageHelper.getNormalImage(getContext(),urlProductImageBean.getHotsales(),mImageViewHot);
        //点击跳转到相应网页
        mLineHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",urlProductImageBean.getHotsalesLink());
                bundle.putString("title","火热促销");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        ImageHelper.getNormalImage(getContext(),urlProductImageBean.getDailyFood(),mImageViewDaliy);
        //点击跳转到相应网页
        mLineDaily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",urlProductImageBean.getDailyFoodLink());
                bundle.putString("title","每日知食");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        ImageHelper.getNormalImage(getContext(),urlProductImageBean.getTodayEat(),mImageViewEat);
        //点击跳转到相应网页
        mLineEat.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Intent intent = new Intent(getActivity(), WebViewActivity.class);
               Bundle bundle = new Bundle();
               bundle.putString("link",urlProductImageBean.getTodayEatLink());
               bundle.putString("title","试吃福利");
               intent.putExtras(bundle);
               startActivity(intent);
           }
       });
    }

    //view的回调，适配listView中item的数据
    @Override
    public void addToRecAdapter(Object object) {

        HomeBaseAdapter adapter = new HomeBaseAdapter(getContext(),
                (List<ListLcBean>) object);
         mListView.setAdapter(adapter);
}
    //整站精选
    @Override
    public void addJingXuanData(final RollListBean rollListBean) {
        mTVJingXuan.setText(rollListBean.getTitle());
        mTVSubJingXuan.setText(rollListBean.getSubTitle());
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecJingXuan.setLayoutManager(linearLayoutManager);
       //添加间距（分割线）
        mRecJingXuan.addItemDecoration(new DividerItemDecoration
                (getContext(), DividerItemDecoration.HORIZONTAL_LIST));
        HomeHRecycleViewAdapter adapter = new HomeHRecycleViewAdapter
                (getContext(),rollListBean.getProductList());
        mRecJingXuan.setAdapter(adapter);
        //设置监听，点击跳转到产品详情页面
       adapter.setOnItemClickListener(new HomeHRecycleViewAdapter.OnItemClickListener() {
           @Override
           public void onItemClick(View view, int position) {
               Intent intent = new Intent(getActivity(),DetailsActivity.class);
               Bundle bundle = new Bundle();
               bundle.putString("product_id", rollListBean.getProductList().get(position).getProductId()+"");
               intent.putExtras(bundle);
               startActivity(intent);
           }
       });
    }
    //新品上市
    @Override
    public void addShangShiData(final RollListBean rollListBean) {
        mTVShangShi.setText(rollListBean.getTitle());
        mTVSubShangShi.setText(rollListBean.getSubTitle());
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecShangShi.setLayoutManager(linearLayoutManager);
        //添加间距（分割线）
        mRecShangShi.addItemDecoration(new DividerItemDecoration
                (getContext(),DividerItemDecoration.HORIZONTAL_LIST));
        HomeHRecycleViewAdapter adapter = new HomeHRecycleViewAdapter
                (getContext(),rollListBean.getProductList());
        mRecShangShi.setAdapter(adapter);
        //设置监听，点击跳转到产品详情页面
        adapter.setOnItemClickListener(new HomeHRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(),DetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("product_id", rollListBean.getProductList().get(position).getProductId()+"");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }
    //view回调，获取新品 上市下面 的两张图片和结尾各两张图片
    @Override
    public void addFourImages(final List<NewBannerListBean> newBannerList) {
       ImageHelper.getNormalImage(getContext(),newBannerList.get(0).getImageUrl(),mIVBiaoZhun);
        //点击跳转到相应网页
        mIVBiaoZhun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",newBannerList.get(0).getLink());
                bundle.putString("title",newBannerList.get(0).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
       ImageHelper.getNormalImage(getContext(),newBannerList.get(3).getImageUrl(),mIVMianFei);
        //点击跳转到相应网页
        mIVMianFei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",newBannerList.get(3).getLink());
                bundle.putString("title",newBannerList.get(3).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
       //尾部两张图片
       ImageHelper.getNormalImage(getContext(),newBannerList.get(1).getImageUrl(),mIVLianMeng);
       //点击跳转到相应网页
        mIVLianMeng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",newBannerList.get(1).getLink());
                bundle.putString("title",newBannerList.get(1).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        ImageHelper.getNormalImage(getContext(),newBannerList.get(2).getImageUrl(),mIVChunBo);
        //点击跳转到相应网页
        mIVChunBo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("link",newBannerList.get(2).getLink());
                bundle.putString("title",newBannerList.get(2).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }
}
